package erfgame.core.graphics.renderer;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;


import erfgame.core.entity.Entity;
import erfgame.core.world.World;


public class ImageEntityRenderer extends AbstractEntityRenderer implements PrototypeEntityRenderer {

	private Image image;
	private Point offset;
	
	private static final BufferedImage createImage( String imagePath ) 
		throws IOException {
		URL imageURL = ImageEntityRenderer.class.getResource( imagePath );
		if( imageURL == null ) {
			throw new IOException( "cannot find "+imagePath );
		}
		return ImageIO.read( imageURL );
	}
	
	private static final BufferedImage decompressImage( BufferedImage image )
	{
		BufferedImage decompressed = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
		Graphics g = decompressed.getGraphics();
		g.drawImage(image, 0, 0, null);
		g.dispose();
		return decompressed;
	}

	public ImageEntityRenderer( String resourcePath ) 
		throws IOException {
		this( decompressImage(createImage( resourcePath )), null, 0 );
	}
	
	public ImageEntityRenderer( Image image ) {
		this( image, null, 0 );
	}

	public ImageEntityRenderer( String resourcePath, Point grabPoint, int depth ) 
		throws IOException {
		this( createImage( resourcePath ), grabPoint, depth );
	}
	
	public ImageEntityRenderer( Image image, Point grabPoint, int depth ) {
		this( image, grabPoint, depth, 0 );
	}
	
	public ImageEntityRenderer( String resourcePath, Point grabPoint, int depth, int border ) 
		throws IOException {
		this( createImage( resourcePath ), grabPoint, depth, border );
	}
	
	public ImageEntityRenderer( Image image, Point grabPoint, int depth, int border ) {
		this( 
				image,
				new Point( border, border ),
				new Dimension( image.getWidth( null ) + border*2, image.getHeight( null ) + border*2 ),
				grabPoint, 
				depth
		);
	}

	public ImageEntityRenderer( String resourcePath, Point offset, Dimension size, Point grabPoint, int depth ) 
		throws IOException {
		this( createImage( resourcePath ), offset, size, grabPoint, depth );
	}

	public ImageEntityRenderer( Image image, Point offset, Dimension size, Point grabPoint, int depth ) {
		super(size, grabPoint==null?new Point(size.width/2, size.height):grabPoint, depth);
		this.image = image;
		this.offset = offset;
	}
	
	public void render(Graphics g, int x, int y) {
		g.drawImage( this.image, x+offset.x, y+offset.y, null );
		//g.drawImage( this.image, x+offset.x-grabPoint.x, y+offset.y-grabPoint.y, null );
	}

	public EntityRenderer spawn( World world, Entity entity ) {
		ImageEntityRenderer result = new ImageEntityRenderer( this.image, this.offset, this.dimension, this.grabPoint, this.depth);
		result.setEntity(entity);
		return result;
	}
	
	
}
